package com.dayang.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;

import com.dayang.dao.BaseDAO;
import com.dayang.model.Client;
import com.dayang.service.OAuthService;

@Service("oAuthService")
public class OAuthServiceImpl implements OAuthService{
	
	private Cache cache;
	
	@Autowired
	private BaseDAO<Client> baseDAO;
	
	   @Autowired
	    public OAuthServiceImpl(CacheManager cacheManager) {
	        this.cache = cacheManager.getCache("code-cache");
	    }

	@Override
	public void addAuthCode(String authCode, String username) {
		 cache.put(authCode, username);
		
	}

	@Override
	public void addAccessToken(String accessToken, String username) {
		 cache.put(accessToken, username);
		
	}

	@Override
	public boolean checkAuthCode(String authCode) {
		 return cache.get(authCode) != null;
	}

	@Override
	public boolean checkAccessToken(String accessToken) {
		 return cache.get(accessToken) != null;
	}

	@Override
	public String getUsernameByAuthCode(String authCode) {
		 return (String)cache.get(authCode).get();
	}

	@Override
	public String getUsernameByAccessToken(String accessToken) {
		  return (String)cache.get(accessToken).get();
	}

	@Override
	public long getExpireIn() {
	long  time =new Date().getTime()+10*60*1000;
		  return time;
	}

	@Override
	public boolean checkClientId(String clientId) {
		Map<String,Object> map = new HashMap<String, Object>();
		String hql=" from Client where clientId=:clientId";
		map.put("clientId", clientId);
		Query query =baseDAO.getHqlQuery(hql, map);
		if(query.list()!=null &&query.list().size()>0){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public boolean checkClientSecret(String clientSecret) {
		Map<String,Object> map = new HashMap<String, Object>();
		String hql=" from Client where clientSecret=:clientSecret";
		map.put("clientSecret", clientSecret);
		Query query =baseDAO.getHqlQuery(hql, map);
		if(query.list()!=null &&query.list().size()>0){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public void addRefreshToken(String refreshToken, String username) {
		 cache.put(refreshToken, username);
		
	}

}
